import os
import time
import traceback
from collections import OrderedDict

import requests
from PyQt5.QtCore import QThreadPool, QRunnable
from bs4 import BeautifulSoup


def get_num(mh_name):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    headers = {
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Mobile Safari/537.36',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?1',
        'sec-ch-ua-platform': '"Android"',
    }

    params = {
        's': f'{mh_name}',
        'cat': '0',
    }
    response = requests.get('https://www.177picyy.com/', params=params, headers=headers)

    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    a_items = (
        soup.find_all("h2", class_="grid-title")
    )
    name_list = []
    namedesc_list = []
    for item in a_items:
        name_list.append(item.find("a").get('href'))
        print(item.find("a").text)
        namedesc_list.append(item.find("a").text)
    return name_list, namedesc_list


def get_pic(http):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    headers = {
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Mobile Safari/537.36',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?1',
        'sec-ch-ua-platform': '"Android"',
    }

    response = requests.get(f'{http}', headers=headers)
    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    a_items = (
        soup.find_all('img', attrs={'data-lazy-src': True})
    )
    b_items = (
        soup.find("div", class_="page-links").find_all("a")
    )
    pic_list = []
    for item in a_items:
        pic_list.append(item.get('data-lazy-src'))
    http_list = []
    for b in b_items:
        http_list.append(b.get('href'))
    pages = list(OrderedDict.fromkeys(http_list))
    print(pages)
    if len(pages) > 0:
        for page in pages:
            headers1 = {
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) '
                              'Chrome/126.0.0.0 Mobile Safari/537.36',
                'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
                'sec-ch-ua-mobile': '?1',
                'sec-ch-ua-platform': '"Android"',
            }

            response = requests.get(f'{page}', headers=headers1)
            print(response.status_code)
            soup = BeautifulSoup(response.text, 'html.parser')
            c_items = (
                soup.find_all('img', attrs={'data-lazy-src': True})
            )
            for item1 in c_items:
                pic_list.append(item1.get('data-lazy-src'))
    return pic_list


def download_image(url, fileName, ix, idx):
    """
    下载图片到本地
    :param idx: 下标
    :param ix: 章节
    :param fileName: 存放文件夹
    :param url: 图片的URL
    """
    try:
        # 发送GET请求获取图片
        response = requests.get(url, stream=True)
        mkdirFile(fileName)
        save_path = f"{fileName}/{ix}_{int(time.time() * 10)}_{idx}.jpg"
        # 检查请求是否成功
        if response.status_code == 200:
            # 打开文件以二进制写模式
            with open(save_path, 'wb') as file:
                # 迭代响应内容，并写入文件
                for chunk in response:
                    file.write(chunk)

            # 如果你安装了Pillow库，可以打开图片以验证下载是否成功
            # img = Image.open(save_path)
            # img.show()

            print(f"Image downloaded successfully to {save_path}")
        else:
            print(f"Failed to download image from {url}. Status code: {response.status_code}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")


def mkdirFile(fileName):
    # 获取当前目录
    current_directory = os.getcwd()
    # 指定要创建的目录路径
    directory = f"{current_directory}/{fileName}"
    # 使用 os.makedirs 创建目录
    # 如果目录已存在，可以设置 exist_ok=True 来避免引发异常
    try:
        os.makedirs(directory, exist_ok=True)
    except OSError as e:
        print(f"创建目录时发生错误: {e}")


class TaskRunnable(QRunnable):
    def __init__(self, data):
        super(TaskRunnable, self).__init__()
        self.data = data

    def run(self):
        # 这里执行你的任务，处理 self.data
        if self.data is None:
            return
        nums_list, namedesc_list = get_num(self.data)
        print(nums_list)
        for ix, num in enumerate(nums_list):
            pic_data = get_pic(num)
            for index, a in enumerate(pic_data):
                download_image(a, namedesc_list[ix], str(ix), index)


if __name__ == '__main__':
    # 多线程 线程池
    threadpool = QThreadPool()
    threadpool.setMaxThreadCount(20)

    list_total = ["3d"
                  ]
    for value in list_total:
        print(f"打印头：{value}")
        runnable = TaskRunnable(value)
        threadpool.start(runnable)
